package com.video.aspect;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.video.entity.TagVlog;
import com.video.entity.Tags;
import com.video.service.TagVlogService;
import com.video.service.TagsService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author baoshuai
 * @date 2022/12/16
 */
@Slf4j
@Component
@Aspect
public class MyAspect {

    @Resource
    private TagsService tagsService;

    @Resource
    private TagVlogService tagVlogService;

    @Pointcut("@annotation(com.video.annotation.InvokeAn)")
    public void pt() {
    }

    @Before("pt()")
    public void calcViewCount(JoinPoint jp) {
        log.info("执行切面方法————增加浏览量");
        Long vlogId = (Long) jp.getArgs()[0];

        //查询vlog对应标签id列表
        LambdaQueryWrapper<TagVlog> tagVlogLambdaQueryWrapper = new LambdaQueryWrapper<>();
        tagVlogLambdaQueryWrapper.eq(TagVlog::getVlogId, vlogId);
        List<Long> tagIds = tagVlogService.list(tagVlogLambdaQueryWrapper).stream()
                .map(TagVlog::getTagId).collect(Collectors.toList());
        //查询所有标签
        List<Tags> tagsList = tagsService.list(null);

        //给对应标签增加浏览量
        for (Tags tag : tagsList) {
            if (tagIds.contains(tag.getId())) {
                tag.setTodayCounts(tag.getTodayCounts() + 1);
                tag.setTotalCounts(tag.getTodayCounts() + 1);
                tagsService.updateById(tag);
            }
        }
    }

}
